package org.biubiu0002.baiblog.im.session;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author: biubiu0002
 * @Date: 2022/8/31 12:33
 **/
@Slf4j
@Component
public class SessionMap {
    private final ConcurrentHashMap<String,ServerSession> map = new ConcurrentHashMap<>();

    /**
     * 增加会话对象
     * @param sessionId 会话id
     * @param session 会话对象
     */
    public void addSession(String sessionId,ServerSession session){
        map.put(sessionId,session);
        log.info("用户登录:id= {}, 在线总数: {}",session.getUser().getUserUid(),map.size());
    }

    /**
     * 获取Session对象
     * @param sessionId sessionId
     * @return session对象
     */
    public ServerSession getSession(String sessionId){
        if(map.containsKey(sessionId)){
            return map.get(sessionId);
        }
        return null;
    }

    public void removeSession(String sessionId){
        ServerSession session = map.get(sessionId);
        if(session==null){
            return;
        }
        map.remove(sessionId);
        log.info("用户退出登录:id= {}, 在线总数: {}",session.getUser().getUserUid(),map.size());

    }

    public void removeSession(ServerSession session){
        map.remove(session.getSessionId());
        log.info("用户退出登录:id= {}, 在线总数: {}",session.getUser().getUserUid(),map.size());


    }

    public List<ServerSession> getSessionsByUid(String uid) {
        return map.values().stream().filter(item -> item.getUser().getUserUid().equals(uid)).collect(Collectors.toList());
    }

    public List<ServerSession> getSessionListByUidList(List<String> uidList){
        HashSet<String> uidSet = new HashSet<>(uidList);
        return map.values().stream().filter(item -> uidSet.contains(item.getUser().getUserUid())).collect(Collectors.toList());
    }

    public List<ServerSession> getSessionListByUidListExceptSession(List<String> uidList, String sessionId) {
        HashSet<String> uidSet = new HashSet<>(uidList);
        return map.values().stream().filter(item -> {
            String userUid = item.getUser().getUserUid();
            return uidSet.contains(userUid)&&!sessionId.equals(item.getSessionId());
        }).collect(Collectors.toList());
    }
}
